package cn.ges.encryption;

import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.AesCipherService;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author gespent@163.com
 * @date 2018/12/10
 */
public class AesEncryption {
    private static final String KEY_ALGORITHM = "AES";

    /**
     * AES 加密操作
     *
     * @param content  待加密内容
     * @param password 加密密码
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String password) {
        SecretKeySpec key = AesEncryption.getSecretKey(password);
        AesCipherService cipherService = new AesCipherService();
        if (key != null) {
            return cipherService.encrypt(content.getBytes(), key.getEncoded()).toHex();
        }
        return null;
    }

    /**
     * AES 解密操作
     */
    public static String decrypt(String content, String password) {
        SecretKeySpec key = AesEncryption.getSecretKey(password);
        AesCipherService cipherService = new AesCipherService();
        if (key != null) {
            return new String(cipherService.decrypt(Hex.decode(content), key.getEncoded()).getBytes());
        }
        return null;
    }

    /**
     * 生成加密秘钥
     */
    public static SecretKeySpec getSecretKey(final String password) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        KeyGenerator kg;

        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);

            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());

            //AES 要求密钥长度为 128
            kg.init(128, random);

            // 生成一个密钥
            SecretKey secretKey = kg.generateKey();
            // 转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
        }

        return null;
    }

}
